package com.top4create.webapp.controller;

import org.apache.commons.lang.StringUtils;
import com.top4create.service.GenericManager;
import com.top4create.model.Company;
import com.top4create.webapp.controller.BaseFormController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Controller
@RequestMapping("/companyform")
public class CompanyFormController extends BaseFormController {
	@Resource(name = "typeManager")
	private GenericManager<Company, Long> typeManager = null;
	private GenericManager<Company, Long> companyManager = null;

	@Autowired
	public void setCompanyManager(
			@Qualifier("companyManager") GenericManager<Company, Long> companyManager) {
		this.companyManager = companyManager;
	}

	public CompanyFormController() {
		setCancelView("redirect:/companies");
		setSuccessView("redirect:/companies");
	}

	@ModelAttribute
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	protected ModelAndView showForm(HttpServletRequest request)
			throws Exception {
		ModelAndView map = new ModelAndView();
		String id = request.getParameter("id");

		if (!StringUtils.isBlank(id)) {
			map.addObject("company", companyManager.get(new Long(id)));
			return map;
		} else {
			map.addObject("company", new Company());
			map.addObject("typeList", typeManager.getAll());
			return map;
		}

	}

	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String onSubmit(Company company, BindingResult errors,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (request.getParameter("cancel") != null) {
			return getCancelView();
		}

		log.debug("entering 'onSubmit' method...");
		boolean isNew = ((company).getId() == null);
		String success = getSuccessView();
		Locale locale = request.getLocale();
		
		if (request.getParameter("delete") != null) {
			companyManager.remove(company.getId());
			saveMessage(request, getText("company.deleted", locale));
		} else {
			companyManager.save(company);
			String key = (isNew) ? "company.added" : "company.updated";
			saveMessage(request, getText(key, locale));

			if (!isNew) {
				success = "redirect:/companyform?id=" + company.getId();
			}
		}

		return success;
	}
}
